﻿namespace Home.Services.OptimizationServices
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Globalization;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Web.Http;
    using System.Web.Http.Dispatcher;
    using System.Web.OData;
    using System.Web.OData.Builder;
    using System.Web.OData.Extensions;
    using System.Xml.Linq;
    using Home.Configuration;
    using Home.Models;
    using Owin;

    public static class OptimizationServiceHelper
    {
        public static void ConfigureOptimizationService(this IAppBuilder app)
        {
            Debug.Assert(app != null);

            //// build EDM model

            var builder = new ODataConventionModelBuilder()
            {
                Namespace = typeof(OptimizationController).Namespace,
                ContainerName = "DefaultContainer"
            };

            {
                builder.EntitySet<OptimizationComment>("Comments");
            }

            {
                builder.EntitySet<OptimizationVisit>("Visits");
            }

            {
                var action = builder.Action("Remove");
                action.Parameter<OptimizationCategory>("category");
                action.Parameter<DateTimeOffset>("time");
                action.Returns<string>();
            }

            var edmModel = builder.GetEdmModel();

            //// configure web API

            var config = new HttpConfiguration();
            if (!ConfigurationHelper.IsProductionEnvironment)
            {
                config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
            }
            config.MessageHandlers.Add(new ETagMessageHandler());
            config.MapODataServiceRoute("OptimizationService", "services/optimizationservice", edmModel);
            config.Services.Replace(typeof(IHttpControllerSelector), new NamespaceAwareHttpControllerSelector(config, typeof(OptimizationController)));
            config.EnsureInitialized();

            app.UseWebApi(config);
        }
    }
}